package com.fsq.utils.seven7z;

import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.google.common.io.Files;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by fshuq on 2017-5-6-0006.
 * 解压文件，带密码
 */
public class UnZip {

    private static final Set<String> errors = Sets.newHashSet();

    public static void main(String[] args) throws IOException, InterruptedException {

        String distPath = System.getProperty("user.dir");

        //获取压缩文件列表
        ArrayList<String> strings = ScanFile.scanDirectoryByExt(distPath, "rar", "zip");

        //获取所有密码
        List<String> codes = codes();

        assert strings != null;
        for (String inputFile : strings) {
            for (String code : codes) {
                if (unzip(inputFile, code, distPath)) {
                    break;
                }
            }
        }

        System.out.println("errors.size() = " + errors.size());
        errors.forEach(error -> {
            try {
                Files.append(error + "\r\n" , new File("error.txt"), Charsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static boolean unzip(String inputFile, String code, String distPath) throws IOException, InterruptedException {
        Runtime runtime = Runtime.getRuntime();
        String cmd = "\"c:\\Program Files\\7-Zip\\7z.exe\" e " + inputFile + " -p" + code + " -aoa -o" + distPath + "";
        System.out.println("cmd = " + cmd);
        Process exec = runtime.exec(cmd);
        String s;
        boolean flag = true;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        while ((s = bufferedReader.readLine()) != null) {
//            System.out.println("s = " + s);
            if (s.contains("Errors") || s.contains("ERRORS") || s.contains("Can't") || s.contains("Wrong")){
                errors.add(inputFile);
                flag = false;
            }
        }
        bufferedReader.close();
        exec.waitFor();
        if (flag) errors.remove(inputFile);
        return flag;
    }

    private static List<String> codes() throws IOException {
        String currentPath = System.getProperty("user.dir");
        return Files.readLines(new File(currentPath + File.separator + "codes.txt"), Charsets.UTF_8);
    }

}
